package com.shopx.hr.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.shopx.core.utils.DateTimeUtil;
import com.shopx.core.utils.HttpUtils;
import com.shopx.core.utils.Md5Encrypt;
import com.shopx.hr.bean.EmployeeLevel;
import com.shopx.hr.dao.db3.EmployeeLevelDao;
import com.shopx.hr.model.EmployeeLevelModel;
import com.shopx.hr.service.IEmpLevelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lituo
 * @version 1.0
 * @description: TODO
 * @date 2025/8/13 上午11:03
 */
@Service
@Slf4j
public class EmpLevelServiceImpl implements IEmpLevelService {
    @Resource
    private EmployeeLevelDao employeeLevelDao;

    @Value("${crm.key}")
    private String crmKey;

    @Value("${crm.reqUrl}")
    private String reqUrl;

    public void syncLevelEmpList(){
        String curDt = DateTimeUtil.getDate8();
        String lastDt = DateTimeUtil.dateCalc(curDt,null,"D",-1);
        log.info("syncLevelEmpList.begin:{}",lastDt);
        EmployeeLevelModel model = new EmployeeLevelModel();
        model.setStartDate(lastDt);
        List<EmployeeLevel> list = employeeLevelDao.selectList(model);
        log.info("syncLevelEmpList.size:{}",list.size());
        //调用CRM接口，置员工为离职状态
        Long time = System.currentTimeMillis();
        String token = Md5Encrypt.md5(crmKey+time);
        log.info("syncLevelEmpList.token:{}",token);
        //调用CRM接口
        //转换数组
        Map reqMap = new HashMap();
        List<Map<String,Object>> empList = new ArrayList<>();
        for(EmployeeLevel record:list){
            Map<String, Object> param = new HashMap<>();
            param.put("CardId",record.getEmployeeIdcard());
            param.put("ResignTime",record.getLeaveDate());
            empList.add(param);
        }
        reqMap.put("Data",empList);
        String jsonArrayStr = JSONUtil.toJsonStr(reqMap);
        log.info("reqUrl:{}",reqUrl+"/api/Security/User/HrDisabledUserAysnc");
        log.info("jsonArrayStr:{}",jsonArrayStr);
        log.info("HRToken:{}",token);
        log.info("TimeSpan:{}",time);
        HttpResponse response = HttpRequest.post(reqUrl+"/api/Security/User/HrDisabledUserAysnc") // 示例接口（可替换）
                .header("Content-Type", "application/json;charset=UTF-8") // 设置请求头
                .header("HRToken",token)
                .header("TimeSpan",String.valueOf(time))
                .body(jsonArrayStr) // 设置请求体
                .timeout(10000) // 超时时间（毫秒）
                .execute();
        log.info("lastDt.syncLevelEmpList.res.status:{},body;{}:"+response.getStatus(),response.body());
    }
}
